<template>
  <div class="filter-container">
    <el-card shadow="hover">
      <el-form :model="filterForm" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <!-- 学期输入 -->
          <el-col :span="8">
            <el-form-item label="学期" prop="semester">
              <el-select
                v-model="filterForm.semester"
                multiple
                filterable
                allow-create
                placeholder="请选择或输入学期"
                :default-first-option="true"
              />
            </el-form-item>
          </el-col>

          <!-- 周次选择 -->
          <el-col :span="8">
            <el-form-item label="周次" prop="weeks">
              <el-select
                v-model="filterForm.weeks"
                multiple
                placeholder="请选择周次"
              >
                <el-option
                  v-for="week in 20"
                  :key="week"
                  :label="`第${week}周`"
                  :value="week"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 时间片输入 -->
          <el-col :span="8">
            <el-form-item label="星期/节次" prop="day_periods_str">
              <el-select
                v-model="filterForm.day_periods_str"
                multiple
                filterable
                allow-create
                placeholder="格式：三/3-4"
                :default-first-option="true"
              />
            </el-form-item>
          </el-col>
<!--          反查无课的老师 no_schedule 点击勾选为true-->
          <el-col :span="8">
            <el-form-item label="反查:" prop="no_schedule">
              <el-switch v-model="no_schedule" active-text="查无课" inactive-text="查有课" />
            </el-form-item>
          </el-col>


          <!-- 其他过滤条件 -->
          <el-col v-for="item in otherFilters" :key="item.prop" :span="8">
            <el-form-item :label="item.label" :prop="item.prop">
              <el-select
                v-model="filterForm[item.prop]"
                multiple
                filterable
                allow-create
                :placeholder="`请选择或输入${item.label}`"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 结果表格 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <el-table :data="courses.data" border stripe>
        <el-table-column
          v-for="col in tableColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          min-width="120"
        />
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.page_size"
        :total="courses.total_count"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        style="margin-top: 20px"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import {jsonApi} from "@/global.js";
import {ElMessage} from "element-plus";

// 默认学期函数（根据实际需求修改）
const getDefaultSemester = () => {
  // 这里实现你的默认学期逻辑
  const date = new Date();
  const currentYear = date.getFullYear();
  const month = date.getMonth() + 1; // 月份范围 1-12

  // 判断学期
  const semester = month >= 2 && month <= 7 ? '春季学期' : '秋季学期';

  // 计算学年
  const startYear = month >= 8 ? currentYear : currentYear - 1;
  const academicYear = `${startYear}-${startYear + 1}`;

  return [`${academicYear}学年${semester}`];

}

// 初始数据
const initialForm = () => ({
  data_filter: {
    semester: getDefaultSemester(),
    course_nums: [],
    course_names: [],
    sequence_number: [],
    weeks: [],
    day_periods: [],
    day_periods_str: [],
    teacher_nums: [],
    teacher_names: [],
    classrooms: []
  },
  page: 1,
  page_size: 8
})
// 响应式数据
const filterForm = reactive(initialForm().data_filter)
const no_schedule = ref(false)
const pagination = reactive({
  page: initialForm().page,
  page_size: initialForm().page_size
})
const courses = reactive({
  data: [],
  total_count: 0
})

// 验证规则
const validateDayPeriods = (rule, values, callback) => {
  // 1. 确保 values 是数组类型（非空且非 null）
  console.log(values)
  if (!values || !Array.isArray(values)) {
    return callback();
  }

  const dayPattern = /^[一二三四五六日]$/; // 单个中文字符
  const periodPattern = /^\d+(?:-\d+)?$/; // 数字或数字范围（如3或3-4）

  const errors = [];

  for (const value of values) {
    // 2. 处理空字符串或无效值
    if (!value || typeof value !== 'string') {
      errors.push('无效的条目：必须为字符串格式');
      continue;
    }

    const trimmedValue = value.trim();
    const parts = trimmedValue.split('/').map(part => part.trim());

    // 3. 格式验证：必须且仅有一个斜杠
    if (parts.length !== 2) {
      errors.push(`格式错误：${value} 必须包含且仅包含一个斜杠，例如“三/3-4”`);
      continue;
    }

    const [dayPart, periodPart] = parts;

    // 4. 验证日期部分
    if (!dayPattern.test(dayPart)) {
      errors.push(`日期部分“${dayPart}”无效，应为“一”到“日”中的一个单个字符`);
      continue;
    }

    // 5. 验证时间段部分
    if (!periodPattern.test(periodPart)) {
      errors.push(`时间段“${periodPart}”格式错误，应为数字或数字范围（如3或3-4）`);
      continue;
    }

    // 6. 可选：验证数值合理性（如起始时间 <= 结束时间）
    const [startStr, endStr] = periodPart.split('-');
    const start = parseInt(startStr, 10);
    const end = endStr ? parseInt(endStr, 10) : start;

    if (isNaN(start) || (endStr && isNaN(end))) {
      errors.push(`时间段中的数字无效：${periodPart}`);
    } else if (endStr && end < start) {
      errors.push(`时间段结束时间“${end}”不能小于起始时间“${start}”`);
    }
  }

  // 7. 统一返回错误或通过验证
  if (errors.length > 0) {
    return callback(new Error(errors.join('\n')));
  }

  callback(); // 验证通过，不带参数
};

const rules = {
  semester: [{ type: 'array', message: '请选择学期' }],
  weeks: [{ type: 'array', message: '请选择周次' }],
  day_periods_str: [{ type: 'array', message: '请选择星期节次' },{ validator: validateDayPeriods }],
  course_nums: [{ type: 'array'}],
  course_names: [{type: 'array'}],
  sequence_number: [{type: 'array'}],
  teacher_nums: [{type: 'array'}],
  teacher_names: [{type: 'array'}],
  classrooms: [{type: 'array'}]
}

// 其他过滤项配置
const otherFilters = [
  {prop: 'course_nums', label: '课程编号'},
  {prop: 'course_names', label: '课程名称'},
  {prop: 'sequence_number', label: '序列号'},
  {prop: 'teacher_nums', label: '教师编号'},
  {prop: 'teacher_names', label: '教师姓名'},
  {prop: 'classrooms', label: '教室'}
]

// 表格列配置
const tableColumns = [
  {prop: 'semester', label: '学期'},
  {prop: 'course_num', label: '课程编号'},
  {prop: 'course_name', label: '课程名称'},
  {prop: 'sequence_number', label: '序列号'},
  {prop: 'teacher_num', label: '教师编号'},
  {prop: 'teacher_name', label: '教师姓名'},
  {prop: 'week', label: '周次'},
  {prop: 'day_of_week', label: '星期'},
  {prop: 'period', label: '节次'},
  {prop: 'classroom', label: '教室'}
]
//转换时间片
const convertDayPeriods = (strList) => {
  if (!strList || strList.length === 0) {
    return [];
  }

  const dayMap = { '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '日': 7 };
  const result = [];

  for (const str of strList) {
    const parts = str.trim().split('/');

    // 忽略格式错误的条目
    if (parts.length < 2) continue;

    const [dayPart, periodPart] = parts;
    const day = dayMap[dayPart] || parseInt(dayPart, 10);

    const periodSplit = periodPart.split('-');
    const [startStr, endStr] = periodSplit;
    const start = parseInt(startStr, 10);
    const end = endStr ? parseInt(endStr, 10) : start;

    result.push({ day, start, end });
  }

  return result;
};
// 表单提交
const handleSubmit = async () => {
  try {
    // 这里调用API
    filterForm.day_periods = convertDayPeriods(filterForm.day_periods_str)
    // 移除 day_periods_str
    // 添加
    const params = {
      data_filter: filterForm,
      no_schedule: no_schedule.value,
      ...pagination
    }
    const response= await jsonApi('/teachingarrangementmanagement/course_get/', JSON.stringify(params))
    if (response.ok) {
      const res = await response.json()
      // 处理响应数据
      if (res?.courses) {
        // 更新课程数据
        courses.data = res.courses.data.map(item => ({
          ...item,
          // 转换星期数字为中文显示（可选）
          day_of_week: ['一', '二', '三', '四', '五', '六', '日'][item.day_of_week - 1] || item.day_of_week
        }));

        // 更新分页信息
        pagination.page = res.courses.page;
        courses.total_count = res.courses.total_count;
      }
      // const res = await api(params)
      // courses.data = res.courses.data
      // courses.total_count = res.courses.total_count
    }else{
      ElMessage.error('获取课程信息失败')
    }
  } catch (error) {
    console.error(error)
  }
}

// 分页变化
const handlePageChange = () => {
  handleSubmit()
}

// 重置表单
const handleReset = () => {
  Object.assign(filterForm, initialForm().data_filter)
  pagination.page = 1
  handleSubmit()
}
</script>

<style scoped>
.filter-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.el-card {
  border-radius: 8px;
}

.el-form-item {
  margin-bottom: 18px;
}
</style>